<?php

namespace app\store\controller\content;


use app\store\controller\BaseController;
use app\store\model\Article;
use app\store\service\ArticleService;
use app\store\service\ArticleCategoryService;
use think\exception\ValidateException;
use think\facade\View;

class ArticleController extends BaseController
{
    public function index()
    {
        $param = $this->request->param();

        $articleCategoryOptions = ArticleCategoryService::getArticleCategoryOption();

        $ArticleService = new ArticleService();
        $list = $ArticleService->getArticleList($param);

        if(!$this->request->isPjax()){
            View::engine()->layout(true);
        }

        return View::fetch('',['articleCategoryOptions' => $articleCategoryOptions, 'list' => $list]);
    }
    
    public function create()
    {
        $articleCategoryOptions = ArticleCategoryService::getArticleCategoryOption();

        return View::fetch('', ['articleCategoryOptions' => $articleCategoryOptions]);
    }

    public function edit()
    {   
        $id = $this->request->get('id/d');

        $articleCategoryOptions = ArticleCategoryService::getArticleCategoryOption();

        $ArticleService = new ArticleService();
        $row = $ArticleService->findArticle($id);

        return View::fetch('',['articleCategoryOptions' => $articleCategoryOptions, 'row' => $row]);
    }

    public function save()
    {
        $param = $this->request->post();
        
        try{
            validate('ArticleValidate')->check($param);
        }catch (ValidateException $e){
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        $param['store_id'] = session('store_id');

        $model =  Article::create($param);

        return !empty($model['id']) ? json(['code' => 1, 'msg' => '保存成功!']) : json(['code' => 0, 'msg' => '保存失败!']);
        
    }

    public function switch()
    {
        $param = $this->request->post();

        try {
            validate('ArticleValidate.switch')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        Article::update($param);

        return json(['code' => 1, 'msg' => '更新成功!']);
    }

    public function update()
    {
        $param = $this->request->post();
        
        try{
            validate('ArticleValidate.edit')->check($param);
        }catch (ValidateException $e){
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        $model =  Article::update($param);

        return !empty($model['id']) ? json(['code' => 1, 'msg' => '更新成功!']) : json(['code' => 0, 'msg' => '更新失败!']);
    }


    public function delete()
    {
        $id = $this->request->get('id/d');

        $res = Article::destroy($id);

        return  $res ? json(['code' => 1,'msg' => '删除成功!']) : json(['code' => 0, 'msg' => '删除失败']);

    }
}